<?php

namespace app\api\controller\v2;

use app\admin\model\cms\Channels;
use app\admin\model\cms\Comment;
use app\admin\model\cms\IntroduceModel;
use app\admin\model\cms\Live;
use app\admin\model\cms\LiveCategoryModel;
use app\admin\model\cms\NewsCategoryModel;
use app\admin\model\cms\Plate;
use app\admin\model\cms\Platepost;
use app\admin\model\cms\VideoCategoryModel;
use app\admin\model\CutWordIndex;
use app\admin\model\Investment;
use app\admin\model\InvestmentCategoryModel;
use app\admin\model\User;
use app\api\service\cms\AttachmentService;
use app\api\service\cms\CacheService;
use app\api\service\JieBaFenCi;
use app\api\service\TengxunSignatureUtil;
use app\common\controller\Api;
use app\common\model\Attachment;
use app\common\model\ChartParent;
use app\common\model\UserFavorite;
use app\common\model\UserLike;
use think\Config;
use think\Model;

/**
 * 分类简介表控制器
 */
class Introduce extends Api
{
    //无需登录的方法,同时也就不需要鉴权了
    //protected $noNeedLogin = ['*'];
    //无需鉴权的方法,但需要登录
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    //获取列表
    public function getList()
    {
        $user = $this->auth->getUser();//用户信息
        $keyword = $this->request->param('keyword', '');//关键词
        $channels_id = $this->request->param('channels_id', '');//分类id|channels.id,可能是顶级也可能是子集分类。
        $page = $this->request->param('page', '1');
        $limit = $this->request->param('limit', '10');
        $orderway = $this->request->param('orderway', 'desc');

        $channels = Channels::where('id', $channels_id)->field('id,parent_id,correlation_id')->find();
        if (!$channels) {
            $this->error('分类id不正确');
        }

        //判断是不是顶级分类，如果是顶级分类就拿全部的子集分类。
        if (!$channels['parent_id']) {
            $channels_id = Channels::where('parent_id', $channels_id)->column('id');
            $channels_id = implode(',', $channels_id);
        }

        //$channels_id到这里是1个或多个二级分类的id
        //循环这些分类看谁在我购买的权限数组中,如果不在我购买的权限数组中就看用户是否购买了单个分类的权限
        //最后返回一个数组,这个$channels_id数组,这个数组就是可显示的富文本文章的分类id
        //如果$channels_id是空,则直接返回空
        $channels_id_arr = array_values(array_filter(explode(',', $channels_id)));
        $channels_id = $this->isPrivilege($user, $channels_id_arr);

        if (!$channels_id){
            $this->success('', [
                'total' => 0,
                'data' => []
            ]);
        }

        $model = IntroduceModel::whereIn('channels_id', $channels_id);
            if($keyword){
                //查询分词索引表->得到文章id
                $cut_word_index = new \app\api\service\cms\CutWordIndex();
                $a_id = $cut_word_index->getCutWordIndex($keyword, 'introduce')['a_id'];
                if ($a_id) {
                    $model = $model->whereIn('id', $a_id);
                }else{
                    $res = [
                        'total' => 0,
                        'data' => [],
                    ];
                    $this->success('', $res);
                }
            }

        $model = $model->with(['admin', 'channels'])
            ->order('id', $orderway)
            ->paginate($limit, false, ['page' => $page])
            ->toArray();

        $res = [
            'total' => $model['total'],
            'data' => [],
        ];

        //附件列表
        $attachment_url_arr = [];
        foreach ($model['data'] as $v) {
            if ($v['file_data']) {
                $attachment_url_arr = array_merge($attachment_url_arr, explode(',', $v['file_data']));
            }
        }
        //获取附件列表
        $attachment_list = (new AttachmentService())->getList(['url' => array_unique(array_filter($attachment_url_arr))]);

        foreach ($model['data'] as $v) {

            $file_img = [];
            foreach (explode(',', $v['file_img']) as $path) {
                $file_img[] = obsurl($path);
            }
            $file_video = [];
            foreach (explode(',', $v['file_video']) as $path) {
                $file_video[] = obsurl($path);
            }
            $file_audio = [];
            foreach (explode(',', $v['file_audio']) as $path) {
                $file_audio[] = obsurl($path);
            }
            $file_data = [];
            if ($v['file_data']) {
                $v['file_data'] = explode(',', $v['file_data']);
                foreach($v['file_data'] as $fv){
                    foreach ($attachment_list as $av) {
                        if ($av['url'] == $fv){
                            if ($keyword){
                                if (strpos($av['filename'], $keyword) !== false){
                                    $file_data[] = [
                                        'filename' => $av['filename'],
                                        'url' => obsurl($av['url'])
                                    ];
                                }
                            }else{
                                $file_data[] = [
                                    'filename' => $av['filename'],
                                    'url' => obsurl($av['url'])
                                ];
                            }

                        }
                    }
                }
            }

            $res['data'][] = [
                'id' => $v['id'],
                'content' => $v['content'],
                'file_img' => array_filter($file_img),
                'file_img_count' => count(array_filter($file_img)),
                'file_video' => array_filter($file_video),
                'file_video_count' => count(array_filter($file_video)),
                'file_audio' => array_filter($file_audio),
                'file_audio_count' => count(array_filter($file_audio)),
                'file_data' => array_filter($file_data),
                'file_data_count' => count(array_filter($file_data)),
                'admin_id' => $v['admin_id'],
                'admin' => [
                    'id' => $v['admin']['id'],
                    'nickname' => $v['admin']['nickname'],
                    'avatar' => obsurl($v['admin']['avatar']),
                ],

                'channels_id' => $v['channels_id'],
                'channels' => [
                    'id' => $v['channels']['id'],
                    'name' => $v['channels']['name'],
                    'parent_id' => $v['channels']['parent_id'],
                    'correlation_id' => $v['channels']['correlation_id'],
                ],
                'createtime' => $v['createtime'] ? date('Y-m-d H:i', $v['createtime']) : '',
            ];
        }
        $this->success('', $res);

    }

    /**
     * 是否拥有权限
     * @param $user
     * @param array $channels_id_arr 二级分类数组
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function isPrivilege($user, $channels_id_arr)
    {
        $free_channels_id_arr = [];//免费的二级channels_id
        $res_channels_id_arr = [];//最终要返回的二级channels_id
        $table_name = '';//自有分类表名称
        $table_name_id_arr = [];//自有分类id
        $channels_model_arr = [];//全部channels表的二级分类

        //看$channels_id_arr中那些二级分类是免费的,免费的不进行验证,那些二级分类是需要付费进行验证
        $channels_model = Channels::whereIn('id', $channels_id_arr)->field('id,parent_id,correlation_id')->select();

        if (!$channels_model) {
            return $res_channels_id_arr;
        }

        foreach ($channels_model as $v) {
            $table_name_id_arr[] = $v['correlation_id'];
            $channels_model_arr[] = $v->toArray();
        }
        //获取table_name的名称
        switch ($channels_model_arr[0]['parent_id']) {
            /*case '1':
                $table_name = 'plate';//首页广场已废弃
                break;*/
            case '2':
                $table_name = 'chart_parent';//量化辅助
                $category_model = new ChartParent();
                break;
            case '3':
                $table_name = 'plate';//债市论坛
                $category_model = new Plate();
                break;
            case '4':
                $table_name = 'video_category';//成长计划
                $category_model = new VideoCategoryModel();
                break;
            case '5':
                $table_name = 'news_category';//新闻资讯
                $category_model = new NewsCategoryModel();
                break;
            case '6':
                $table_name = 'live_category';//直播专区
                $category_model = new LiveCategoryModel();
                break;
            case '7':
                $table_name = 'investment_category';//数据库
                $category_model = new InvestmentCategoryModel();
                break;
        }
        //获取免费的自用栏目的id
        $_category_arr = $category_model->whereIn('id', $table_name_id_arr)
            ->field('id,membership_price')
            ->select();
        if ($_category_arr) {
            foreach ($channels_model_arr as &$v) {
                $v['membership_price'] = '0.00';
                foreach ($_category_arr as $vv) {
                    if ($v['correlation_id'] == $vv['id']) {
                        $v['membership_price'] = $vv['membership_price'];
                    }
                }
                if ($v['membership_price'] < 0.01) {
                    $free_channels_id_arr[] = $v['id'];
                }
            }
        }

        $new_user = new User();
        $rule_column_id = $new_user->isChannelsPermission($user)['rule_column_id'];//当前用户拥有权限的的全部栏目二级Channels_id
        //判断是否开通分类会员
        $membershipExpiryRecord = new MembershipExpiryRecord();

        foreach ($channels_model_arr as $v) {
            //判断这个分类id在不在我的权限列表中,在就直接返回
            if (in_array($v['id'], $rule_column_id)) {
                $res_channels_id_arr[] = $v['id'];
                continue;//跳过本次循环进入下一次循环
            }

            //判断当前分类是否免费
            if (in_array($v['id'], $free_channels_id_arr)) {
                $res_channels_id_arr[] = $v['id'];
                continue;//跳过本次循环进入下一次循环
            }

            //判断用户是否买来了当前分类
            $isMemberExpire = $membershipExpiryRecord->isMemberExpire($user['id'], 'categories', $table_name, $v['correlation_id']);
            if ($isMemberExpire['code'] == '200') {
                $res_channels_id_arr[] = $v['id'];
                continue;//跳过本次循环进入下一次循环
            }
        }
        return array_values(array_unique($res_channels_id_arr));
    }


}
